package org.andu.java_gobang.controller;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.andu.java_gobang.mapper.UserMapper;
import org.andu.java_gobang.pojo.User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class UserAPI {
    @Resource
    private UserMapper userMapper;

    @PostMapping("/login")
    @ResponseBody
    public Object login(String username, String password, HttpServletRequest request) {
        User user = userMapper.selectByName(username);
        System.out.println("[login] username: " + username);
        if (user == null || !password.equals(user.getPassword())) {
            System.out.println("登陆失败");
            return new User();
        }
        HttpSession httpSession = request.getSession(true);
        httpSession.setAttribute("user", user);
        return user;
    }

    @PostMapping("/register")
    @ResponseBody
    public Object register(String username, String password) {
        try {
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            userMapper.insert(user);
            return user;
        } catch (org.springframework.dao.DuplicateKeyException e) {
            User user = new User();
            return user;
        }
    }

    @GetMapping("/userInfo")
    @ResponseBody
    public Object getUserInfo(HttpServletRequest request){
        try {
            //不允许再新建会话
            HttpSession httpSession = request.getSession(false);
            User user = (User) httpSession.getAttribute("user");
            //用Session的user对象去数据库中查询
            User newUser = userMapper.selectByName(user.getUsername());
            return newUser;
        }catch (NullPointerException e){
            return new User();
        }
    }

    @GetMapping("/getAllUsers")
    @ResponseBody
    public List<User> getAllUsers(){
        List<User> allUsers = userMapper.getAllUsers();
        return allUsers;
    }
}
